/**
 * @Description: 短信验证码
 * @Author: rcc
 * @Date: 2024-8-28 22:05:25
 */

import { ref } from 'vue'

import { codeDuration } from '@/configs/index.ts'

/**
 * 验证码类型
 *
 * - 1: 登录
 * - 2: 注册
 * - 3: 修改手机
 * - 4: 修改密码
 */
type CodeType = 1 | 2 | 3 | 4

export default function useCode() {
	const codeText = ref('获取验证码')

	let sending = false
	let codeTimer = 0
	let countdown = codeDuration

	/**
	 * 发送验证码
	 *
	 * @param {string} mobile - 手机号码.
	 * @param {CodeType} type - 验证类型.
	 * @returns {Promise<void>} 返回说明.
	 */
	const sendCode = async (mobile: string, type: CodeType): Promise<void> => {
		if (mobile === '') {
			uni.$u.toast('请输入手机号')
			return
		}

		if (sending) return

		sending = true
		uni.showLoading({ title: '发送中...', mask: true })

		const data = {
			type,
			mobile,
		}

		const res = await uni.$u.post('/sendsms/index', data)

		uni.$u.toast(res.msg)
		if (res.code === 1) {
			startCountdown()
		} else {
			sending = false
		}
	}

	/**
	 * 开始倒计时
	 */
	const startCountdown = () => {
		setCodeText()

		codeTimer = setInterval(() => {
			if (countdown <= 0) {
				sending = false
				setCodeText(true)
				clearCodeTimer()
			} else {
				setCodeText()
			}
		}, 1000)
	}

	/**
	 * 设置发送按钮文字
	 *
	 * @param {boolean} [isReset=false] - 是否重置按钮文字.
	 */
	const setCodeText = (isReset: boolean = false) => {
		if (isReset) {
			countdown = codeDuration
			codeText.value = '获取验证码'
		} else {
			countdown--
			codeText.value = `${countdown}秒`
		}
	}

	/**
	 * 清除发送验证码定时器
	 */
	const clearCodeTimer = () => {
		clearInterval(codeTimer)
	}

	return {
		codeText,
		sendCode,
		clearCodeTimer,
	}
}
